package com.duk.log;

import java.text.SimpleDateFormat;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.Mongo;

public class MongoLogger
{

	public static final String SEQUENCE_COLL = "sequence";
	public static final String SEQUENCE_NAME = "bizlog";

	private DB db;

	private DBCollection bizColl;

	private String collName;

	/**
	 * 构造器,供spring使用构造器方式注入
	 * 
	 * @param db
	 * @param collName
	 */
	public MongoLogger(Mongo mongo, String dbName, String collName)
	{
		this.collName = collName;
		try
		{
			this.db = mongo.getDB(dbName);
			this.bizColl = db.getCollection(collName);
		} catch (Exception e)
		{
			System.out.println("MongoLogger初始化失败");
			e.printStackTrace();
		}
	}

	/**
	 * 得到下一个id
	 * 
	 * @return
	 */
	private Integer getNextId()
	{
		DBCollection table = db.getCollection(SEQUENCE_COLL);
		DBObject query = new BasicDBObject();
		query.put("name", SEQUENCE_NAME);
		DBObject newDocument = new BasicDBObject();
		newDocument.put("$inc", new BasicDBObject().append("value", 1));
		DBObject ret = table.findAndModify(query, newDocument);
		if (ret == null)
		{
			throw new RuntimeException("获得id失败");
		} else
		{
			return (Integer) ret.get("value") + 1;
		}
	}

	public DBCollection getBizColl()
	{
		return bizColl;
	}

	public void setBizColl(DBCollection bizColl)
	{
		this.bizColl = bizColl;
	}

	/**
	 * 增加mongodb日志
	 */
	public void addLogger(BizLogData log)
	{
		DBObject obj = new BasicDBObject();
		obj.put("_id", getNextId());
		obj.put("code", log.getCode());
		obj.put("operation", log.getOperation());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if (log.getOperateTime() != null)
		{
			obj.put("time", sdf.format(log.getOperateTime()));
		}
		obj.put("operator", log.getOperator());
		obj.put("success", log.getSuccess());
		obj.put("ip", log.getIp());
		obj.put("params", log.getParams());
		bizColl.insert(obj);
	}

}
